package com.atguigu.gmall.controller;

import com.atguigu.gmall.entity.Person;
import com.atguigu.gmall.entity.User;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class InvertController {

    public static void main(String[] args) {
        List<User> users = Arrays.asList(
                new User(1L, "小美", 20, 0),
                new User(2L, "明明", 21, 1),
                new User(3L, "红红", 18, 0),
                new User(4L, "小强", 22, 1),
                new User(5L, "环环", 26, 0)
        );

        // 初始化stream 中间操作 终止操作
        // filter(过滤出符合条件的集合)   map(集合转换)   reduce(求总和)
        users.stream()
                .filter(user -> user.getAge() > 21)
                .collect(Collectors.toList())
                .forEach(user -> System.out.println(user));

        System.out.println("----------------------------------------");

        List<String> list = users.stream()
                .map(User::getName)   // 方法引用：User::getName 相当于 user -> user.getName()
                .collect(Collectors.toList());
        System.out.println(list);

        System.out.println("-----------------------------------------");

        // 将User转换成Person
        System.out.println(users.stream()
                .map(user -> {
                    Person person = new Person();
                    person.setUserName(user.getName());
                    person.setAge(user.getAge());
                    return person;
                }).collect(Collectors.toList()));

        System.out.println("-----------------------------------------");

        Optional<Integer> sum = users.stream()
                .map(User::getAge)
                .reduce((a, b) -> a + b);
        System.out.println("年龄之和：" + sum.get());

    }
}
